package com.lc.sell.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lc.sell.dto.CartDTO;
import com.lc.sell.dto.OrderDTO;
import com.lc.sell.dto.OrderListDTO;
import com.lc.sell.emnus.OrderStatusEnum;
import com.lc.sell.emnus.PayStatusEnum;
import com.lc.sell.emnus.ResultEnum;
import com.lc.sell.entity.Order;
import com.lc.sell.entity.OrderDetail;
import com.lc.sell.entity.Product;
import com.lc.sell.entity.User;
import com.lc.sell.exception.SellException;
import com.lc.sell.mapper.OrderMapper;
import com.lc.sell.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.sell.service.UserService;
import com.lc.sell.service.WebSocket;
import com.lc.sell.util.AliPayUtil;
import com.lc.sell.util.IdGenerator;
import com.lc.sell.util.TimeUtils;
import com.lc.sell.vo.OrderListVO;
import com.lc.sell.vo.OrderPay;
import com.lc.sell.vo.ResultVo;
import com.lc.sell.vo.UserOrderListVO;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 龙晨
 * @since 2022-02-01
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ProductServiceImpl productService;
    @Autowired
    private OrderDetailServiceImpl orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocket webSocket;

    @Override
    @Transactional
    public ResultVo createOrder(OrderDTO orderDTO) {
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);
        String orderID = IdGenerator.genUniqueKey();
        //1.查询商品（数量，价格）
        for (OrderDetail orderDetail : orderDTO.getGoods()) {
            Product product = productService.getById(orderDetail.getId());
            if (product == null){
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            //2.计算订单总价
            orderAmount = product.getPrice().multiply(new BigDecimal(orderDetail.getNumber())).add(orderAmount);
            //订单详情入库
            orderDetail.setCreatedTime(TimeUtils.getNowDate());
            orderDetail.setDetailId(IdGenerator.genUniqueKey());
            orderDetail.setOrderId(orderID);
            orderDetail.setMid(product.getMid());
            BeanUtils.copyProperties(product,orderDetail);
            orderDetailService.save(orderDetail);
        }
        Order order = new Order();
        orderDTO.setCreated_at(TimeUtils.getNowDate());
        orderDTO.setCompleted_time(null);
        orderDTO.setOrder_no(orderID);
        orderDTO.setSort_num(IdGenerator.QchGenerator());
        orderDTO.setStatus(OrderStatusEnum.NEW.getCode());
        orderDTO.setAmount(orderAmount);
        BeanUtils.copyProperties(orderDTO,order);
        order.setPayStatus(PayStatusEnum.PAY_STATUS_WX.getCode());
        orderMapper.insert(order);
        List<CartDTO> collect = orderDTO.getGoods()
                .stream()
                .map(e -> new CartDTO(e.getId(), e.getNumber()))
                .collect(Collectors.toList());
        productService.updateStock(collect);
        //加销量
        productService.addSold(collect);
        //减用户金额
        User user = userService.getById(orderDTO.getUserId());
        BigDecimal balance = user.getBalance();
        user.setBalance(balance.subtract(orderAmount));
        userService.update(user,new QueryWrapper<User>().eq("customerId",user.getCustomerId()));
        webSocket.sendMessage("你有新的订单请及时查收!");
        return ResultVo.ok("订单",orderDTO);
    }

    @Override
    public List<OrderListVO> findAllNewOrder(Integer mid) {
        return orderMapper.findAllNewOrder(mid);
    }

    @Override
    @Transactional
    public ResultVo updateOrderStatus(String oid) {
        Order order = orderMapper.selectById(oid);
        Integer status = order.getOrderStatus();
        if (status == 1) {
            status += 1;
        }else if(status == 2){
            if (order.getTypeCate() == 2){
                status += 1;
            }else{
                status += 2;
            }
        }else if (status == 3){
            status += 1;
        }
        orderMapper.updateOrderStatus(oid, status);
        return ResultVo.ok("修改成功");
    }

    @Override
    public ResultVo orderList(Integer mid) {
        List<Order> order = orderMapper.orderList(mid);
        return ResultVo.ok("查询成功",order);
    }

    @Override
    public ResultVo userOrderList(Integer uid) {
        List<UserOrderListVO> userOrderListVOS = orderMapper.userOrderList(uid);
        return ResultVo.ok("查询成功",userOrderListVOS);
    }

    @Override
    public ResultVo selectOrderStatus(String orderId) {
        Order order = orderMapper.selectById(orderId);
        return ResultVo.ok("订单状态为：",order.getOrderStatus());
    }

    @Override
    public ResultVo updateOrderReview(String orderId,Integer review) {
        Order order = orderMapper.selectById(orderId);
        order.setReview(review);
        orderMapper.update(order,new QueryWrapper<Order>().eq("order_id",orderId));
        return ResultVo.ok("修改成功");
    }

    @Override
    public ResultVo alipayTradeWapPay(OrderPay orderPay) {
        //===================这里你可以保存你的订单和支付宝订单信息（商户号和订单金额需要保存，支付宝异步回调时需要根据商户号处理业务逻辑）======================
        //（1）封装统一支付接口并调用
        String out_trade_no = IdGenerator.getDateTimeAndRandomForID();//生成商户订单号
        String total_amount = orderPay.getBalance();//交易金额
        String pay_result = AliPayUtil.alipayTradeWapPay(out_trade_no, total_amount);
        if(!(pay_result).isEmpty()) {
//            User user = new User();
//            user.setBalance(new BigDecimal(orderPay.getBalance()));
//            user.setCustomerId(orderPay.getCustomerId());
//            userService.updUser(user);
            return ResultVo.ok(999999, "操作成功", pay_result);
        }else {
            return ResultVo.fail("支付宝调取异常");
        }
    }
}
